package com.lsh.account.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lsh.account.dao.AccountDao;
import com.lsh.account.entity.Account;
import com.lsh.account.feign.OrderApi;
import com.lsh.account.feign.StorageApi;
import com.lsh.account.repository.AccountRepository;
import com.lsh.account.service.AccountService;
import com.lsh.common.util.ResultObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LiuShihao
 */
@Slf4j
@Service("AccountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountRepository accountRepository;
    @Autowired
    OrderApi orderApi;
    @Autowired
    StorageApi storageApi;
    @Autowired
    private AccountDao accountDao;


    /**
     * 扣减账户余额
     * @param userId 用户id
     * @param money 金额
     */
    @Override
    public void decrease(Integer userId, Integer money) {
        log.info("------->扣减账户开始");
        //模拟超时异常，全局事务回滚
//        try {
//            Thread.sleep(30*1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        accountRepository.decrease(userId,money);
        accountDao.decrease(userId,money);
        log.info("------->扣减账户结束");

        //修改订单状态，此调用会导致调用成环

        log.info("修改订单状态开始");
        Integer status = 0 ;
        String mes = orderApi.update( userId, money,status);
        log.info("修改订单状态结束：{}",mes);
    }

    @Override
    public List<Account> findAll() {
        return accountRepository.findAll();
    }

    @Override
    public List<Account> findAllByMyBatis() {
        return accountDao.findAllByMyBatis();
    }

    @Override
    public Object findAllStorage() {
        ResultObject resultObject = JSONObject.parseObject(storageApi.findAll(), ResultObject.class);
        return  resultObject.getData();
    }
}
